<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>  {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="onEdit(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>

              <el-popconfirm title="确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="center">
        <!-- 放置分页组件 -->
        <el-pagination
          :current-page="pageParams.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageParams.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageParams.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <!-- 弹层 -->
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="onCancel">
        <!-- 表单内容 -->
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用">
            <el-switch v-model="roleForm.state" size="mini" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="onSubmit">确定</el-button>
                <el-button size="mini" @click="onCancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 分配权限弹层 -->
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <!-- 放置权限数据 -->
        <el-tree
          ref="permTree"
          node-key="id"
          :data="permissionData"
          :props="{ label: 'name' }"
          show-checkbox
          default-expand-all
          :default-checked-keys="permIds"
        />
        <div style="text-align: center;margin-top: 10px;">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { addRole, getRoleList, delRole, updateRole, assignPerm, getRoleDetail } from '@/api/role'
import { transObjToTree } from '@/utils/index.js'
import { getPermissionListApi } from '@/api/permission.js'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      showDialog: false,
      // 表单内容
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }],
        description: [{ required: true, message: '角色描述不能为空', trigger: ['blur', 'change'] }]
      },
      // ------------
      showPermissionDialog: false, // 控制分配权限弹层显示隐藏
      permissionData: [], // 存储权限列表
      currentRoleId: null, // 记录当前点击的分配权限的id
      permIds: [] // 存储当前已有的权限
    }
  },
  watch: {
    'roleForm.state'(newValue, oldValue) {
      console.log(newValue, oldValue)
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { page, pagesize } = this.pageParams
      const { rows, total } = await getRoleList({ page, pagesize })
      this.list = rows
      this.pageParams.total = total
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        // 添加一个对象进行数据缓存
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    handleSizeChange(pageSize) {
      // 切换页面条数
      // console.log('我是pageSize', pageSize)
      this.pageParams.pagesize = pageSize
      this.getRoleList()
    },
    handleCurrentChange(page) {
      // 切换分页
      // console.log('我是current', current)
      this.pageParams.page = page
      this.getRoleList()
    },
    async onSubmit() {
      await this.$refs.roleForm.validate()
      await addRole(this.roleForm)
      this.getRoleList()
      this.$message.success('新增成功')
      this.onCancel()
    },
    onCancel() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    async confirmDel(id) {
      // 删除
      // console.log(id)
      await delRole(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    btnEditRow(row) {
      // 改变isEdit的值
      row.isEdit = true
      // 点击的时候更新缓存的数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 编辑行内数据
    async onEdit(row) {
      // 1. 数据校验
      if (!row.editRow.name.trim() || !row.editRow.description.trim()) {
        this.$message.warning('角色名称和描述不能为空~')
        return
      }
      // 2. 调用接口
      await updateRole({ id: row.id, ...row.editRow })
      this.$message.success('修改角色成功~')
      // 3. 退出编辑
      // row.isEdit = false
      Object.assign(row, {
        isEdit: false,
        ...row.editRow
      })
    },
    // 分配权限
    async btnPermission(id) {
      this.currentRoleId = id
      this.permissionData = transObjToTree(await getPermissionListApi(), 0)
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      // 点击确定提交已选中的权限
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>
<style scoped>
  .role-operate {
  padding: 10px;
}
</style>
